package demo2;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-07-25
 * Time: 10:26
 */
public class MyStack2 {

    private static final int DEFAULT_CAPACITY = 10;

    public int[] elem;

    public static int usedSize;

    public MyStack2() {
        this.elem = new int[DEFAULT_CAPACITY];
    }

    /**
     * 压栈方法
     *
     * @param val 压栈值
     * @return 返回压栈的元素
     */
    public int push(int val) {

        // 判断数组是否需要扩容
        if (isFull()) {
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }

        elem[usedSize++] = val;

        return val;
    }

    private boolean isFull() {
        return usedSize >= elem.length;
    }

    /**
     * 出栈方法
     *
     */
    public int pop() throws EmptyException {

        // 栈为空无法弹出
        if (empty()) {
            throw new EmptyException("栈为空, 无法弹出");
        }
        return elem[--usedSize];
    }

    /**
     * 判断栈是否为空
     */
    public boolean empty() {
        return usedSize == 0;
    }

    /**
     * 查看栈顶元素
     */
    public int peek() {
        if (empty()) {
            throw new EmptyException("栈为空, 暂无元素可查看");
        }

        return elem[usedSize - 1];
    }
}
